package net

import (
	"data-system/controller"
	"data-system/models"
	"encoding/json"
	"log"
	"sync"

	"github.com/gorilla/websocket"
)

type Receiver struct {
	Id         string
	conn       *websocket.Conn
	msgChannel chan models.XMessage
	closeChan  chan struct{}
	wg         *sync.WaitGroup
}

func NewReceiver(id string, conn *websocket.Conn, msgChannel chan models.XMessage, wg *sync.WaitGroup) *Receiver {
	return &Receiver{
		Id:         id,
		conn:       conn,
		msgChannel: msgChannel,
		closeChan:  make(chan struct{}),
		wg:         wg,
	}
}

func (r *Receiver) Watch() {
	defer r.wg.Done()
	defer close(r.msgChannel)
	for {
		select {
		case <-r.closeChan:
			return
		default:
			_, reqMessage, err := r.conn.ReadMessage()
			if err != nil {
				if websocket.IsUnexpectedCloseError(err) {
					log.Println("【消息监听】读取错误:", err)
				}
				close(r.closeChan)
				return
			}
			// 消息处理（可替换为业务逻辑）
			log.Printf("【消息监听】：receiver: %s", reqMessage)
			var req models.Req
			json.Unmarshal(reqMessage, &req)
			var respMessage models.XMessage
			router, err := controller.RouteHandler(r.msgChannel, r.conn, req)
			if err != nil {
				respMessage = models.BuildFailMessage(req.Uuid, req.Action, err.Error())
			} else {
				res, err := router.Handle()
				if err != nil {
					respMessage = models.BuildFailMessage(req.Uuid, req.Action, err.Error())
				} else {
					if res != nil {
						respMessage = models.BuildOkMessage(req.Uuid, req.Action, res)
					}
				}
			}
			select {
			case r.msgChannel <- respMessage:
			case <-r.closeChan:
				return
			}
		}
	}
}
